const path = require('path')
const fs = require('fs')

const ejs = require('ejs')

const compile = (templateName, data) => {
  const templatePosition = `../templates/${templateName}`
  const templatePath = path.resolve(__dirname, templatePosition)

  return new Promise((resolve, reject) => {
    ejs.renderFile(templatePath, {data}, {}, (err, result) => {
      if(err) {
        console.log(err)
        reject(err)
        return
      }
      resolve(result)
    })
  })
}

const mkdirSync = (pathName) => {
  if(fs.existsSync(pathName)) {
    return true
  } else {
    // 不存在,判断父亲文件夹是否存在？
    if(mkdirSync(path.dirname(pathName))) {
      // 存在父亲文件，就直接新建该文件
      fs.mkdirSync(pathName) 
      return true
    }
  }
}

const writeToFile = (path, content) => {
  if (fs.existsSync(path)) {
    log.error("the file already exists~")
    return;
  }
  return fs.promises.writeFile(path, content);
}

module.exports = {
  compile,
  writeToFile,
  mkdirSync
}